package com.lc.springboot.config.shiro;

import com.lc.springboot.mapper.SysUserMapper;
import com.lc.springboot.model.SysUser;
import com.lc.springboot.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 身份验证
 *
 * @author lengchuan <lishuijun1992@gmail.com>
 * @date 16-8-30
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    SysUserMapper sysUserMapper;


    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //用户名
        String name = (String) token.getPrincipal();
        //获取用户
        SysUser sysUser = sysUserService.getUserByName(name);

        if (sysUser == null) {
            throw new UnknownAccountException("用户不存在");//用户名不存在
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                sysUser.getLoginName(), //用户名
                sysUser.getPassword(), //密码
                ByteSource.Util.bytes(sysUser.getSalt()),//salt=springboot
                getName()); //realm name

        return authenticationInfo;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //用户名
        System.out.println("-------------------------------->授权");
        String name = (String) principals.getPrimaryPrincipal();
        Set<String> roles=sysUserService.findUserRoles(name);
        Set<String> menus=sysUserService.findUserMenus(name);

        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(menus);

        return authorizationInfo;
    }


  public static void main(String[] args) {
        String password =new Md5Hash("admin","springboot",2).toString();
        System.out.println(password);//a962bd673e9ac6e24f88ac939acb8882
    }
}
